package com.lankystar.logistucs.spring.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.lankystar.logistucs.spring.dao.IUserDao;
import com.lankystar.logistucs.spring.entity.Company;
import com.lankystar.logistucs.spring.entity.User;

@Repository
public class UserDaoImpl extends BaseDaoImpl implements IUserDao{

	@Autowired
	private SessionFactory sf;
	public Session getSession(){
		System.out.println("session userDaoImpl");
		return sf.getCurrentSession();
	}
	@Override
	public User selectUserById(Integer userId) {
		User user = (User) getSession().get(User.class, userId);
		return user;
	}

	@Override
	public User selectUserByUserPhoneAndUserPassword(String userPhone, String userPassword) {
		User user = (User) getSession().createQuery("from User u where u.userPhone = ? and u.userPassword = ? and u.usual = ?")
				.setString(0, userPhone).setString(1, userPassword).setInteger(2, 0).uniqueResult();
		return user;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<User> selectUserlist(int userKey) {
		String sql = "select u from User u join u.userType ut where ut.userKey = ? and u.remove = ?";
		List<User> userlist = getSession().createQuery(sql).setInteger(0, userKey).setInteger(1, 0).list();
		return userlist;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<User> selectCanUserlist() {
		String sql = "select u from User u join u.truckStatus ts join u.company cp where ts.truckStatusKey = 1";
		List<User> userlist = getSession().createQuery(sql).list();
		return userlist;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Object[]> selectCompanyUserlist(int userId) {
		String hql = "select cp from User u  join u.company cp where u.userId = ? ";
		Company company = (Company) getSession().createQuery(hql).setInteger(0, userId).uniqueResult();
		String sql = "select u,ts from User u join u.truckStatus ts join u.company cp where cp.companyId = ?";
		List<Object[]> userlist = getSession().createQuery(sql).setInteger(0, company.getCompanyId()).list();
		return userlist;
	}
	@Override
	public Object[] selectUserAndUserTypeById(int userId) {
		String hql = "from User u join u.userType ut where u.userId = ?";
		Object[] ob = (Object[]) getSession().createQuery(hql).setInteger(0, userId).uniqueResult();
		return ob;
	}

}
